package com.ksm.zyz.common.util;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UploadUtil {

	/**
	 * 从request中取得批量上传的文件
	 * 
	 * @param req
	 * @return
	 */
	public List<MultipartFile> getFiles(HttpServletRequest req) {
		MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
		Map<String, MultipartFile> map = mreq.getFileMap();
		List<MultipartFile> fileList = new ArrayList<MultipartFile>();
		for (Object obj : map.values()) {
			MultipartFile file = (MultipartFile) obj;
			fileList.add(file);
		}
		return fileList;
	}

	/**
	 * 从request中取得特定的文件
	 * 
	 * @param req
	 * @param fileName
	 * @return
	 */
	public MultipartFile getFile(HttpServletRequest req, String fileName) {
		MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
		return mreq.getFile(fileName);
	}

	public void upload(MultipartFile file, String path) throws IOException {
		FileOutputStream out = new FileOutputStream(path);
		FileCopyUtils.copy(file.getBytes(), out);
	}

	/**
	 * 写入文件到本地目录并返回图片名称和本地上传路劲
	 * @param imgFile
	 * @param typeName
	 * @param brandName
	 * @param fileTypes
	 * @return
	 */
	public static Map<String,String> getFile(MultipartFile imgFile, String folderName, String provinceName) {
		Map<String,String> fileMap = new HashMap<String, String>();
		String fileName = imgFile.getOriginalFilename();
		String ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		ext = ext.toLowerCase();
		File file = null;
		String platform = System.getProperty("os.name","No Define System name!");
		String filePath = "";
		if (platform.toLowerCase().indexOf("windows") != -1) {
			filePath = "d:\\zyz\\"+folderName+"\\" + provinceName+"\\";
		} else {
			filePath = "/opt/zyz/"+folderName+"/"+provinceName+"/";
		}
		File dpath = new File(filePath);
		if (!dpath.exists()){
			dpath.mkdirs();
		}
		String realFilePath = dpath+"\\"+fileName;
		if (ext.equals("jpg")) { // 如果扩展名属于允许上传的类型，则创建文件
			file = new File(dpath,fileName);
			try {
				imgFile.transferTo(file); // 保存上传的文件
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		fileMap.put("fileName", fileName);
		fileMap.put("filePath", realFilePath);
		return fileMap;
	}
}
